const request = require('../../../api/request');
const { getImageUrl } = require('../../../utils/image');
const app = getApp();
Page({
  data: {
    news: {},
    comments: [],
    showCommentPanel: false,
    liked: false
  },
  onLoad(options) {
    console.log('详情页 onLoad options:', options);
    const id = options.id;
    if (!id) {
      console.error('未获取到id，无法加载详情');
      wx.showToast({ title: '无效的动态ID', icon: 'none' });
      return;
    }
    
    // 检查是否已点赞
    const isLiked = wx.getStorageSync(`liked_news_${id}`);
    this.setData({ liked: isLiked });
    
    this.loadDetail(id);
    // 增加浏览量
    this.increaseViewCount(id);
  },
  // 格式化时间
  formatTime(isoTime) {
    if (!isoTime) return '';
    
    try {
      // 移除ISO时间中的T和毫秒部分
      const dateStr = isoTime.replace('T', ' ').split('.')[0];
      
      // 创建日期对象
      const date = new Date(isoTime);
      if (isNaN(date.getTime())) {
        // 如果日期无效，尝试直接返回清理后的字符串
        return dateStr;
      }
      
      // 格式化为 YYYY-MM-DD HH:MM
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    } catch (e) {
      console.error('时间格式化错误:', e);
      return isoTime || '';
    }
  },
  loadDetail(id) {
    console.log('调用loadDetail，id:', id);
    const url = `/family-news/${id}`;
    console.log('请求动态详情接口:', url);
    console.log('当前token:', wx.getStorageSync('token'));
    request.get(url)
      .then(res => {
        console.log('详情接口返回数据:', res);
        // 字段适配并处理图片URL
        const cover_image = getImageUrl(res.coverImage || res.cover_image || res.image);
        const author_avatar = getImageUrl(res.authorAvatar || res.author_avatar || res.avatar);
        
        // 格式化时间
        const created_at = this.formatTime(res.createdAt || res.created_at);
        const publish_time = this.formatTime(res.publish_time);
        
        this.setData({
          news: {
            id: res.id,
            cover_image,
            author_avatar,
            author_name: res.authorName || res.author_name || '',
            title: res.title,
            content: res.content,
            description: res.description,
            type: res.type,
            view_count: res.viewCount || res.view_count || 0,
            like_count: res.likeCount || res.like_count || 0,
            created_at,
            publish_time,
            // 其他字段按需补充
          }
        });
      })
      .catch(err => {
        console.error('详情接口返回:', err);
        wx.showToast({ title: err.msg || '加载失败', icon: 'none' });
      });
  },
  // 增加浏览量
  increaseViewCount(id) {
    const url = `/family-news/${id}/view`;
    request.post(url)
      .then(res => {
        console.log('浏览量增加成功:', res);
        // 更新本地浏览量显示
        if (res && res.view_count) {
          this.setData({
            'news.view_count': res.view_count
          });
        }
      })
      .catch(err => {
        console.error('增加浏览量失败:', err);
        // 浏览量增加失败不做提示，不影响用户体验
      });
  },
  onLike() {
    if (this.data.liked) return;
    const url = `/family-news/${this.data.news.id}/like`;
    request.post(url)
      .then(res => {
        this.setData({
          'news.like_count': res.like_count || (this.data.news.like_count + 1),
          liked: true
        });
        wx.vibrateShort();
      })
      .catch(err => {
        wx.showToast({ title: err.msg || '点赞失败', icon: 'none' });
      });
  },
  showComments() {
    this.setData({ showCommentPanel: true });
    this.loadComments();
  },
  loadComments() {
    const url = `/family-news/${this.data.news.id}/comments`;
    request.get(url)
      .then(res => {
        this.setData({ comments: res.list || [] });
      })
      .catch(err => {
        wx.showToast({ title: err.msg || '加载评论失败', icon: 'none' });
      });
  },
  onComment(e) {
    const content = e.detail.value.content;
    if (!content) return;
    const url = `/family-news/${this.data.news.id}/comment`;
    request.post(url, { content })
      .then(() => {
        wx.showToast({ title: '评论成功' });
        this.loadComments();
      })
      .catch(err => {
        wx.showToast({ title: err.msg || '评论失败', icon: 'none' });
      });
  }
}); 